﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Dict.Blo;

namespace UI
{
    public class HeroSelectPage : Page
    {
        public GameObject scrollView;
        public GameObject itemPrefab;
        public SimpleGrid simpleGrid;
        public GameObject nextPageWordPref; //"点击显示下一页"
        public UIToggle checkBox;

        public delegate void SelectHeroCallback(List<string> guids);
        public SelectHeroCallback m_callback;

        Dictionary<string,GameObject> heroItems = new Dictionary<string, GameObject>();
        Dictionary<string, string> selectGuids = new Dictionary<string, string>();
        //List<string> selectGuids = new List<string>();
        List<string> outSelectGuids = new List<string>();
        List<string> availableGuids = new List<string>();
        string guid;    //要被升级的hero
        long totalExp = 0;  //已选择的卡牌经验综合
        long maxExpAllow;   //不超过主角等级时最多可选经验
        float waitTime = 0;
        int curShowedCount = 0;

        public void OnConfirmBtn()
        {
            List<string> list = new List<string>();
            foreach (var s in selectGuids)
                list.Add(s.Key);

            if(m_callback != null)
            {
                m_callback(list);
            }

            Close();
        }

        IEnumerator UpdatePanel()
        {
            foreach(var item in heroItems)
            {
                Destroy(item.Value);
            }
            heroItems.Clear();

            foreach (var item in simpleGrid.childs)
            {
                Destroy(item);
            }
            simpleGrid.childs.Clear();
            yield return new WaitForSeconds(waitTime);
            
            if (curShowedCount == 0)
            {
                availableGuids = StaticData.playerData.InstPlayerData.GetHeroUpgradeAvailableListInOrder();
                foreach(var a in availableGuids)
                {
                    if (a == guid)
                    {
                        availableGuids.Remove(a);
                        break;
                    }
                }
            }
            int count = 0;
            for (int i = curShowedCount; i < availableGuids.Count; i++)
            {
                GameObject obj = Instantiate(itemPrefab);
                simpleGrid.AddChild(obj);
                obj.GetComponent<ChoseHeroItem>().SetHero(availableGuids[i],true);
                obj.GetComponent<ChoseHeroItem>().checkBox.GetComponent<UIDragScrollView>().scrollView = scrollView.GetComponent<UIScrollView>();
                obj.GetComponent<ChoseHeroItem>().m_OnCheckBox = this.OnChoseItemValueChange;
                heroItems[availableGuids[i]] = obj;

                count++;
                if (count % 14 == 0)
                    yield return 1;
                if (count % 160 == 0 && i + 1 < availableGuids.Count)
                {
                    GameObject nextPageWordObj = Instantiate(nextPageWordPref);
                    nextPageWordObj.SetActive(true);
                    nextPageWordObj.GetComponent<NextPageWord>().m_callback = this.OnNextPage;
                    simpleGrid.AddChild(nextPageWordObj);
                    break;
                }
            }
            curShowedCount += count;
            scrollView.GetComponent<UIScrollView>().ResetPosition();
            
            //选中曾经选中的
            foreach (var item in outSelectGuids)
            {
                OnChoseItemValueChange(item, true);
            }
        }

        void OnNextPage()
        {
            waitTime = 0.01f;
            StopCoroutine("UpdatePanel");
            StartCoroutine(UpdatePanel());
        }

        /// <summary>
        /// 只处理手动打钩和取消，自动选进入此函数
        /// </summary>
        /// <param name="heroguid"></param>
        /// <param name="value"></param>
        void OnChoseItemValueChange(string heroguid,bool value)
        {
            UIHero hero = StaticData.playerData.GetUIHero(heroguid);
            if (hero == null)
                return;
            if (value)
            {
                long tempexp = hero.GetHeroProvideExp();
                //如果将要超过主角等级则拒绝选中并飘字   FK
                if (totalExp >= maxExpAllow)
                {
                    heroItems[heroguid].GetComponent<ChoseHeroItem>().checkBox.GetComponent<UIToggle>().value = false;
                    BoxManager.CreatePopupTextBox(TableTextBlo.GetText("already_chosed_enough_materail").Replace("\\r", "\r").Replace("\\n", "\n"));
                }
                else
                {
                    heroItems[heroguid].GetComponent<ChoseHeroItem>().checkBox.GetComponent<UIToggle>().value = true;
                    totalExp += tempexp;
                    selectGuids[heroguid] = heroguid;
                }
            }
            else
            {
                selectGuids.Remove(heroguid);
                totalExp -= hero.GetHeroProvideExp();
            }
        }

        public void OnOneKeySelect()
        {
            //清空之前的选择
            foreach (var item in heroItems)
            {
                item.Value.GetComponent<ChoseHeroItem>().checkBox.GetComponent<UIToggle>().value = false;
            }

            selectGuids.Clear();
            totalExp = 0;
            if(checkBox.value)
            {
                int count = 0;
                for(int i = 0; i < availableGuids.Count; i++)
                {
                    //TODO!!!!! 经验卡还没处理
                    UIHero hero = StaticData.playerData.GetUIHero(availableGuids[i]);
                    if ((hero.heroData.quality < (int)QualityValue.BLUE || hero.heroData.heroClass == (int)HeroClass.Exp_Eater) && heroItems.ContainsKey(hero.guid))
                    {
                        long tempexp = hero.GetHeroProvideExp();
                        if (totalExp > maxExpAllow)
                        {
                            break;
                        }
                        else
                        {
                            count++;
                            heroItems[availableGuids[i]].GetComponent<ChoseHeroItem>().checkBox.GetComponent<UIToggle>().value = true;
                            totalExp += tempexp;
                            selectGuids[availableGuids[i]] = availableGuids[i];
                            if (count >= 40)
                                break;
                        }
                    }
                }
                if (totalExp <= 0)
                {
                    //没有蓝色以下的卡可自动添加
                    checkBox.value = false;
                    BoxManager.CreatePopupTextBox(TableTextBlo.GetText("no_card_under_blue").Replace("\\n", "\n").Replace("\\r", "\r"));
                    return;
                }
            }
        }

        protected override void DoOpen()
        {
            guid = options["guid"];

            selectGuids.Clear();
            totalExp = 0;
            checkBox.Set(false);
            
            outSelectGuids.Clear();
            string[] outSelected = options["selected"].Split(',');
            for (int i = 0; i < outSelected.Length; i++)
            {
                outSelectGuids.Add(outSelected[i]);
            }

            //最多可选经验
            UIHero heroTo = StaticData.playerData.GetUIHero(guid);
            int maxLevel = DictHeroExpBlo.GetHeroMaxLevel(heroTo.heroData.quality);
            int nextlevel = StaticData.playerData.level < maxLevel ? StaticData.playerData.level + 1 : maxLevel;
            long exp1 = DictHeroExpBlo.GetHeroExpToLevel(heroTo.heroData.quality, heroTo.level);
            long exp2 = DictHeroExpBlo.GetHeroExpToLevel(heroTo.heroData.quality, nextlevel);
            maxExpAllow = exp2 - exp1 - heroTo.exp;

            base.DoOpen();

            GetComponent<PageTweener>().Play();

            waitTime = 0.5f;
            curShowedCount = 0;
            StopCoroutine("UpdatePanel");
            StartCoroutine(UpdatePanel());

        }

        protected override void DoClose()
        {
            foreach (var item in simpleGrid.childs)
            {
                Destroy(item);
            }
            simpleGrid.childs.Clear();
            base.DoClose();
        }
    }
}
